package com.lagou.zk;

import org.I0Itec.zkclient.IZkDataListener;

import java.sql.Connection;
import java.util.concurrent.CountDownLatch;

/**
 * @Author Cao Dun
 * @Date 2021/3/23 22:12
 * @Version 1.0
 * @Description 监听zk集群数据库连接池信息，实现数据库连接池信息的改动
 */
public class DbPoolIZkDataListener implements IZkDataListener {

    PutGetCfg putGetCfg;
    Connection connection;
    CountDownLatch countDownLatch;

    public DbPoolIZkDataListener(PutGetCfg putGetCfg, Connection connection ,CountDownLatch countDownLatch) {
        this.putGetCfg = putGetCfg;
        this.connection = connection;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void handleDataChange(String s, Object o) throws Exception {
        System.out.println("数据库连接池信息被改动了");
        //释放连接
        DruidUtils.close(connection);
        //重新获取zk的数据库连接池的信息
        putGetCfg.getCfg();
        //唤醒线程
        countDownLatch.countDown();
    }

    @Override
    public void handleDataDeleted(String s) throws Exception {

    }
}
